package com.zsrd.self.base.runner;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zsrd.self.entity.SelfWxConfig;
import com.zsrd.self.service.SelfWxConfigService;
import com.zsrd.self.util.MySM2Util;
import com.zsrd.self.util.SaltEncryption;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;

/**
 * <pre>
 *
 * </pre>
 *
 * @author sunjiyong
 * @since 2024/4/11 8:29
 */
@Component
public class StartupRunner implements CommandLineRunner {
    private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

    @Autowired
    private SelfWxConfigService selfWxConfigService;

    @Override
    public void run(String... args)  {
        try {
            QueryWrapper<SelfWxConfig> qw = new QueryWrapper();
            qw.eq("oper_flag", "startupRunner");
            SelfWxConfig one = selfWxConfigService.getOne(qw);
            String value = one.getAppId();
            String secret = one.getAppSecret();
            String salt = value.substring(0, 16);
            String real = value.replace(salt, "");
            String rule = SaltEncryption.decrypt(real, salt);
            if (dateCompare(rule)) {
                String newSalt = value.substring(value.length() - 16);
                MySM2Util.privateKey = SaltEncryption.decrypt(secret, newSalt);
                System.out.println("项目启动秘钥添加成功");
            } else {
                System.out.println("数据权限过期，请获取新秘钥");
            }
        }catch (Exception e){
            System.out.println("程序加载秘钥异常"+e.getMessage());
        }

    }


    private boolean dateCompare(String rule){
        LocalDate currentDate = LocalDate.now();
        LocalDate ruleDate = LocalDate.parse(rule,formatter);
        int result = currentDate.compareTo(ruleDate);
        return result<=0;
    }

}
